/**
 * STM32 Dilithium封装层
 * ProvideClass似于STM32硬件加密的接口
 */

#include "stm32f4xx_dilithium.h"
#include "dilithium_impl.h"
#include <string.h>

/* Dilithium上下文（全局） */
static Dilithium_Context dilithium_ctx;
static uint8_t dilithium_initialized = 0;
static uint8_t dilithium_key_set = 0;

/**
 * @brief InitializeDilithiumModule
 */
HAL_StatusTypeDef Dilithium_Init(void)
{
    Dilithium_Impl_Init(&dilithium_ctx);
    dilithium_initialized = 1;
    dilithium_key_set = 0;
    return HAL_OK;
}

/**
 * @brief SettingsDilithiumKey
 */
HAL_StatusTypeDef Dilithium_SetKey(uint8_t* key, uint32_t key_len)
{
    if (!dilithium_initialized) {
        return HAL_ERROR;
    }
    
    if (key == NULL || key_len < 32) {
        return HAL_ERROR;
    }
    
    /* LoadKey种子 */
    Dilithium_LoadKey(&dilithium_ctx, key);
    
    dilithium_key_set = 1;
    return HAL_OK;
}

/**
 * @brief ExecuteDilithiumCommand
 */
HAL_StatusTypeDef Dilithium_ProcessCommand(uint8_t cmd, 
                                           const uint8_t* input, 
                                           uint32_t input_len,
                                           uint8_t* output, 
                                           uint32_t* output_len)
{
    if (!dilithium_initialized || !dilithium_key_set) {
        return HAL_ERROR;
    }
    
    if (input == NULL || output == NULL || output_len == NULL) {
        return HAL_ERROR;
    }
    
    /* According toCommandExecute操作 */
    switch (cmd) {
        case DILITHIUM_CMD_SIGN:
            /* Dilithium签名: Input=消息(32字节), Output=签名(64字节) */
            if (input_len != 32) {
                return HAL_ERROR;
            }
            Dilithium_Sign(&dilithium_ctx, input, output);
            *output_len = 64;
            break;
            
        case DILITHIUM_CMD_VERIFY:
            /* DilithiumVerify: Input=消息(32)+签名(64), Output=Result(1) */
            if (input_len < 96) {
                return HAL_ERROR;
            }
            {
                const uint8_t* msg = input;
                const uint8_t* signature = input + 32;
                int result = Dilithium_Verify(&dilithium_ctx, msg, signature);
                output[0] = result ? 1 : 0;
                *output_len = 1;
            }
            break;
            
        default:
            return HAL_ERROR;
    }
    
    return HAL_OK;
}
